const path = require('path')
const files = require.context('@/base-ui', true, /.vue$/)
import defaultImg from '@/assets/img/R-C.jpg'

import Message from '@/base-ui/message/message'
import Confirm from '@/base-ui/confirm/confirm'

// 自动注册 @/base-ui 下的组件为全局组件
const init = (app) => {
  files.keys().forEach((key) => {
    const name = path.basename(key, '.vue') //返回文件名 不含后缀名
    const content = files(key).default || files(key)
    app.component(name, content)
  })
}
// 自定义指令
const defineDirective = (app) => {
  // 图片懒加载
  app.directive('lazy', {
    mounted(el, binding) {
      const observe = new IntersectionObserver(([{ isIntersecting }]) => {
        if (isIntersecting) {
          observe.unobserve(el)
          el.onerror = () => {
            el.src = defaultImg
          }
          el.src = binding.value
        }
      })
      observe.observe(el)
    }
  })
}

export default {
  install(app) {
    init(app)
    defineDirective(app)
    app.config.globalProperties.$Message = Message
    app.config.globalProperties.$Confirm = Confirm
  }
}
